#include<cstdio>
#include<iostream>
#include<unistd.h>
#include <sys/types.h>

using namespace std;

//函数指针类型
typedef void(*work_t)(int rfd); 
typedef void(*task_t)(int rfd, int id);

//任务
void PrintLog(int rfd, int id)
{
    cout << "rfd: " << rfd << " process: " << id << " is working: " << " printf log task!" << endl;
}

void ReloadConf(int rfd, int id)
{
    cout << "rfd: " << rfd << " process: " << id << " is working: " << " reload conf task!" << endl;
}

void ConnectMysql(int rfd, int id)
{
    cout<< "rfd: " << rfd << " process: " << id << " is working: " << "Connect Mysql task!" << endl;
}

task_t task[3] = {PrintLog, ReloadConf, ConnectMysql };

int NextCode() //2.2.选择要执行任务的编号
{
    return rand() % 3; //生成一个伪随机数
}

void Work(int rfd) //2.4.子进程接受并处理任务
{
    while(true)
    {
        int code = 0; 
        int n = read(0, &code, sizeof(code)); //子进程从管道的读端读取数据
        if(n > 0)  
        {
            if(code >= 3) continue; 
            task[code](rfd, getpid()); 
        }
        else if(n == 0) //情况3,写端关闭,读取到了结尾
        {
            cout << "read ending!" << endl;
            break;
        }
        else 
        {
            cout << "read error!" << endl;
            break;
        }

        sleep(1);
    }
}
